package jasongarrett.spida;

import java.util.ArrayList;
import java.util.List;

public class JobApplication
{
	private JobApplicationService jobApplicationService;
	
	/**
	 * submit an application for Jason Garrett for one of the open positions at Spida Software
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception
	{
		JobApplication ja = new JobApplication();
		ja.setJobApplicationService(new SpidaService());
		String applicationId = ja.apply();
		
		System.out.println();
		System.out.println("The application Id is: " + applicationId);
		System.out.println();
	}
	
	/**
	 * submit an application for Jason Garrett for one of the open positions
	 * @return  the applicationId of the submitted application
	 * @throws Exception
	 */
	public String apply() throws Exception
	{
		// find the job that we're going to apply for
		Job job = getJobToApplyFor();

		// assemble the application for the job
		Application application = buildApplication(job);

		// apply for the job
		String applicationId = submitApplication(application);
		
		// retrieve the submitted application
		Application submittedApplication = getSubmittedApplication(applicationId);
		
		// dump it to the console
		System.out.println(ApplicationJSONConverter.jsonFromApplication(submittedApplication));
		
		return applicationId;
	}

	/**
	 * configure which JobApplicationService to use to submit the application
	 * @param jobApplicationService
	 */
	public void setJobApplicationService(JobApplicationService jobApplicationService)
	{
		this.jobApplicationService = jobApplicationService;
	}
	
	private Job getJobToApplyFor() throws Exception
	{
		List<Job> jobs = jobApplicationService.getJobs();
		return jobs.get(0);
	}
	
	private String submitApplication(Application application) throws Exception
	{
		String applicationId = jobApplicationService.createApplication(application);
		return applicationId;
	}
	
	private Application buildApplication(Job job)
	{
		Application application = new Application();
		application.setJobId(job.get_id());
		application.setName("Jason Garrett");
		application.setJustification("I can write elegant, well tested code.");
		application.setCode("https://jasongarrett-spidasoftware-application.googlecode.com/svn/trunk/");
		
		List<String> additionalLinks = new ArrayList<String>();
		additionalLinks.add("http://www.linkedin.com/in/jasongarrett1/");
		application.setAdditionalLinks(additionalLinks);
		
		return application;
	}
	
	private Application getSubmittedApplication(String applicationId) throws Exception
	{
		Application submittedApplication = jobApplicationService.getApplication(applicationId);
		return submittedApplication;
	}
}
